package com.aopcinemas.visitor.behaviour;

import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;

import com.aopcinemas.cinema.ontology.CinemaOntology;
import com.aopcinemas.cinema.ontology.GetScheduleList;
import com.aopcinemas.visitor.VisitorAgent;

public class ScheduleSearchBehavior extends TickerBehaviour {

    private static final long serialVersionUID = 1L;

    private static final long DEFAULT_PERIOD = 10000;
    private long period = DEFAULT_PERIOD;

    public ScheduleSearchBehavior(Agent agent) {
        super(agent, DEFAULT_PERIOD);// default
    }

    @Override
    protected void onTick() {
        System.out.println("SeachBehavior: " + toString() + " , " + period);

        VisitorAgent agent = (VisitorAgent) myAgent;
        GetScheduleList getScheduleList = agent.getGetScheduleList();
        // is agent.getCampaign() == null is needed here? not logical here...
        if (getScheduleList != null && agent.getCampaign() == null) {
            System.out.println("getScheduleList is not null: " + agent.getCinemas().size());

            if (period != getScheduleList.getPeriod()) {
                reset(period);
                period = getScheduleList.getPeriod();
            }

            ScheduleInfoNotifyBehavior notifier = new ScheduleInfoNotifyBehavior(agent.getCinemas().size());
            agent.addBehaviour(notifier);

            for (AID cinema : agent.getCinemas()) {
                ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
                message.setLanguage(agent.getCodec().getName());
                message.setOntology(CinemaOntology.getInstance().getName());
                message.addReceiver(cinema);
                try {
                    agent.getContentManager().fillContent(message, new Action(cinema, getScheduleList));
                } catch (CodecException e) {
                    e.printStackTrace();
                } catch (OntologyException e) {
                    e.printStackTrace();
                }
                agent.addBehaviour(new ScheduleInfoInitiator(agent, notifier, message));
            }
        }
    }
}
